package cn.jbolt.ec.cloud;

import cn.jbolt._admin.permission.CheckPermission;
import cn.jbolt._admin.permission.PermissionKey;
import cn.jbolt._admin.permission.UnCheckIfSystemAdmin;
import cn.jbolt.base.JBoltBaseController;
import cn.jbolt.common.model.BecApp;
import cn.jbolt.ec.wx.GenService;
import com.qiniu.util.Auth;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@CheckPermission({PermissionKey.RETAILER_MODIFY_LICENSE_IMAGE,
        PermissionKey.OPTION_ADD,PermissionKey.OPTION_UPDATE,
        PermissionKey.COMMODITY_ADD,PermissionKey.COMMODITY_UPDATE,
        PermissionKey.RETAILER_TYPE_ADD,PermissionKey.RETAILER_TYPE_MODIFY})
public class QnController extends JBoltBaseController {


    /**
     * 前端获取key的方法
     * @param suffix
     * @throws Exception
     */

    public void QiniuUpToken(String suffix) throws Exception{
        BecApp becApp = GenService.getApp();
        String accessKey = becApp.getQnAk();
        String secretKey =becApp.getQnSk();
        String bucket = becApp.getQnBucket();

        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //验证七牛云身份是否通过
            Auth auth = Auth.create(accessKey, secretKey);
            //生成凭证
            String upToken = auth.uploadToken(bucket);
            result.put("token", upToken);
            //存入外链默认域名，用于拼接完整的资源外链路径
            result.put("domain", becApp.getQnDomain());

            // 是否可以上传的图片格式
            /*boolean flag = false;
            String[] imgTypes = new String[]{"jpg","jpeg","bmp","gif","png"};
            for(String fileSuffix : imgTypes) {
                if(suffix.substring(suffix.lastIndexOf(".") + 1).equalsIgnoreCase(fileSuffix)) {
                    flag = true;
                    break;
                }
            }
            if(!flag) {
                throw new Exception("图片：" + suffix + " 上传格式不对！");
            }*/

            //生成实际路径名
            String randomFileName = UUID.randomUUID().toString() + suffix;
            result.put("imgUrl", randomFileName);
            result.put("success", 1);
        } catch (Exception e) {
            result.put("message", "获取凭证失败，"+e.getMessage());
            result.put("success", 0);
            return;
        } finally {
            renderJson(result);
        }
    }

}
